package com.example.imtoken.core.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.imtoken.R
import com.xuexiang.xui.utils.WidgetUtils
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog

abstract class BaseFragment<T : BaseViewModel, BD : ViewDataBinding>(private val clz: Class<T>) :
    Fragment() {

    protected val viewModel by lazy {
        ViewModelProvider(requireActivity()).get(clz)
    }

    protected lateinit var dataBinding: BD

    private var baseContent: FrameLayout? = null
    private var views: View? = null

    private var mLoadingDialog: MiniLoadingDialog? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        dataBinding = DataBindingUtil.inflate(inflater, initLayoutId(), container, false)
        return dataBinding.root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        if (KeyboardUtils.isSoftInputVisible(requireActivity())) {
            KeyboardUtils.hideSoftInput(requireActivity())
        }
        init()
//        initObserves()
        mLoadingDialog =
            WidgetUtils.getMiniLoadingDialog(
                requireContext(),
                resources.getString(R.string.pleaseWait)
            )
        mLoadingDialog?.setCancelable(true)
    }

    private fun initObserves() {
        viewModel.mDialog.observe(viewLifecycleOwner) {
            if (it) {
                mLoadingDialog?.show()
            } else {
                mLoadingDialog?.dismiss()
            }
        }
        viewModel.mErrorStr.observe(viewLifecycleOwner) {
            ToastUtils.showShort(it)
        }
        viewModel.mErrorResId.observe(viewLifecycleOwner) {
            ToastUtils.showShort(it)
        }
    }

    abstract fun initLayoutId(): Int
    abstract fun init()

    protected fun <T : BaseViewModel> getViewModel(clz: Class<T>): T {
        return ViewModelProvider(requireActivity()).get(clz)
    }

    protected fun <T : BaseViewModel> getViewModelThis(clz: Class<T>): T {
        return ViewModelProvider(this).get(clz)
    }
}